/**
 * 数字滚动变化
 */

import { _decorator, Component, Node, Label, Tween, tween } from 'cc';
import { BCTools } from '../../utils/BCTools';
const { ccclass, property } = _decorator;

@ccclass('BCRollingLabel')
export class BCRollingLabel extends Label {
	private m_baseNum: number = 0;
	private m_action: Tween<{ num: number }> = null;

	_updateLabelNum(finalNum: number, time: number = 2, isShort: boolean = false) {
		this.m_action && this.m_action.stop();
		this._setNum(this.m_baseNum, isShort);
		if (finalNum<=this.m_baseNum) {
			this._setNum(finalNum, isShort);
			return;
		}
		const obj = {
			num: this.m_baseNum
		};
		this.m_baseNum = finalNum;
		this.m_action = tween(obj).to(time, { num: finalNum }, {
			easing: "sineOut",
			progress: (start: number, end: number, current: number, ratio: number) => {
				const offset = start + (end - start) * ratio;
				this._setNum(offset, isShort);
				return offset;
			},
			onComplete: () => {
				this._setNum(finalNum, isShort);
				this.m_action && this.m_action.stop();
				this.m_action = null;
			}
		});
		this.m_action.start();
	}

	_resetLabel(){
		this.m_baseNum = 0;
		this.string = "0";
	}

	private _setNum(num: number, isShort: boolean){
		this.m_baseNum = num;
		if (isShort) {
			this.string = BCTools.bigNumber2Short(Math.floor(num));
		} else {
			this.string = BCTools.bigNumber2Str(Math.floor(num));
		}
	}
}

